<?php
header('Content-Type: text/html; charset=utf-8');
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Help Desk
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */


require_once(dirname(__FILE__)."/../../../config/config.inc.php");
require_once(dirname(__FILE__).'/../classes/ZticketObject.php');
require_once(dirname(__FILE__).'/../classes/ZdepartmentObject.php');
require_once(dirname(__FILE__).'/../classes/ZticketContentObject.php');
require_once(dirname(__FILE__).'/../classes/ZemailSend.php');

/**
 * @see ZemailGateway.php
 */
require dirname(__FILE__).'/../classes/ZemailGateway.php';
class ZnotificationEmail
{
   /**
    * Run cron
    */
	public function runCron()
	{
		$this->generateNotice();
	}
	
	/**
	 * generate notify
	 */
	public function generateNotice() 
	{
		$cookieLifetime = (time() + (((int)Configuration::get('PS_COOKIE_LIFETIME_FO') > 0 ? (int)Configuration::get('PS_COOKIE_LIFETIME_FO') : 1)* 3600));
		$cookie = new Cookie('ps', '', $cookieLifetime);
		
		$now = time();
		$date = date("Y-m-d h:i:s");
		$noticeTime = (int) ConfigurationCore::get('ZHELPDESK_NOTIFY_MISSED_TICKET');
		$stepNoticeTime = (int) ConfigurationCore::get('NOTIFY_STAFF_INTERVAL');
		$completeTime = (int) ConfigurationCore::get('AUTO_CLOSE_TIME');
//      $noticeTime = $noticeTime*60*60;
//		$stepNoticeTime = $stepNoticeTime*60*60;
//		$completeTime = $completeTime*60*60;
		
		// test time minutes
		$noticeTime = $noticeTime*60;
		$stepNoticeTime = $stepNoticeTime*60;
		$completeTime = $completeTime*60;
		
		$collection =  ZTicketObject::getTicketFilterClose();
		
		echo 'time now :  '.$date.'<br/>';
		/* check working day */
		$listDayWorking = explode(',',Configuration::get ('WORKING_DAY'));
		$timeDay = array (
			'Monday' => 0,
			'Tuesday' => 1,
			'Wednesday' => 2,
			'Thursday' => 3,
			'Friday' => 4,
			'Saturday' => 5,
			'Sunday' => 6,
		);
		$day = date("l");
		$statusTime = 0;
		if (in_array($day, $listDayWorking) ) {
			$time = Configuration::get('WORKING_TIME_'.$day);
			$times = explode (';',$time);
			$timeCurent = time ();
			$time = explode ('-',$times[0]);
			if ($timeCurent >= strtotime($time[0]) && $timeCurent <= strtotime($time[1])) {
				$statusTime = 1;
			}
			$time = explode ('-',$times[1]);
			if ($timeCurent >= strtotime($time[0]) && $timeCurent <= strtotime($time[1])) {
				$statusTime = 1;
			}
		}   
		$test = true;
		if ($statusTime==1 OR $test)
		{
	        foreach ($collection as $ticket) 
	        {
	        	/* ticket open -> miss*/
	        	if ($ticket['id_zhelpdesk_ticket_status'] == 1)
	        	{
	        		$stepReplyTime = strtotime($ticket['date_upd']);
		        	$diffStaff = $now - $stepReplyTime;
		        	
		        	echo 'ticket open -> miss:&nbsp;&nbsp;&nbsp;';
		        	echo $stepNoticeTime.'|'.$diffStaff.'->'.$stepReplyTime.'='.$ticket['date_upd'].'</br>';

		        	if ($stepNoticeTime > 0 AND $stepNoticeTime <= $diffStaff)
		        	{
			        	/* change ticket status from open to missing */
			        	ZTicketObject::setTicketStatus($ticket['id_zhelpdesk_ticket'], 4);
			        	/* update time change status ticket from open to mising */ 
			        	ZTicketObject::updateTicketTime($ticket['id_zhelpdesk_ticket'], $date);
			        	
			        	$modeDepartment = ZdepartmentObject::_getModeById($ticket['id_moderator']);
			        	$namemode = $modeDepartment['firstname'].' '.$modeDepartment['lastname'].' ('.$modeDepartment['email'].')';
			        	$content = ZticketContentObject::getContentTicketMiss($ticket['id_zhelpdesk_ticket']);
			        	/* sent mail notify miss ticket */
			        	$this->_sentMailMiss($ticket['email'], $ticket['firstname'].' '.$ticket['lastname'], $ticket['subject'], $ticket['name_customer'], $ticket['email_customer'], $namemode, $content);
		        	}
	        	}
	        	/* ticket pending -> close*/
	        	elseif ($ticket['id_zhelpdesk_ticket_status'] == 3)
	        	{
	        		$lastReplyTime = strtotime($ticket['date_upd']);
		        	$diffLastReply = $now - $lastReplyTime;
		        	
		        	echo 'ticket pending -> close:&nbsp;&nbsp;&nbsp;';
		        	echo $completeTime.'|'.$diffLastReply.'</br>';
		        	
		        	if ($completeTime > 0 AND $completeTime <= $diffLastReply)
		        	{
			        	/* update ticket status close */
			        	ZTicketObject::setTicketStatus($ticket['id_zhelpdesk_ticket'], 2);
		        	}
	        	}
	        	/* ticket missing ->notify staff */
	        	elseif ($ticket['id_zhelpdesk_ticket_status'] == 4)
	        	{
	        		$missTime = strtotime($ticket['date_upd']);
		        	$diffMiss = $now - $missTime;
		        	
		        	echo 'ticket missing -> notify staff:&nbsp;&nbsp;&nbsp;';
		        	echo $noticeTime.'|'.$diffMiss.'</br>';
		        	
		        	if ($noticeTime > 0 AND $noticeTime <= $diffMiss)
       				{
       					/* update time when ticket mising */ 
		        		ZTicketObject::updateTicketTime($ticket['id_zhelpdesk_ticket'], $date);
		        		
		        		ZTicketObject::updateTicketTime($ticket['id_zhelpdesk_ticket'], $date);
			        	$modeDepartment = ZdepartmentObject::_getModeById($ticket['id_moderator']);
			        	$namemode = $modeDepartment['firstname'].' '.$modeDepartment['lastname'].' ('.$modeDepartment['email'].')';
			        	$content = ZticketContentObject::getContentTicketMiss($ticket['id_zhelpdesk_ticket']);
		        		/* sent mail notify miss ticket */
	        			$this->_sentMailMiss($ticket['email'], $ticket['firstname'].' '.$ticket['lastname'], $ticket['subject'], $ticket['name_customer'], $ticket['email_customer'], $namemode, $content);
       				}
		        	
	        	}
			}
        }  	
	}
	
	/**
	 * sent mail for staff when mis ticket
	 * 
	 * @param email $email to address email
     * @param char $emailName name email
     * @param char $subject subject email
	 */
	public function _sentMailMiss($email, $emailName, $subject, $customer_name, $customer_email, $namemode, $content)
	{
		$cookieLifetime = (time() + (((int)Configuration::get('PS_COOKIE_LIFETIME_FO') > 0 ? (int)Configuration::get('PS_COOKIE_LIFETIME_FO') : 1)* 3600));
		$cookie = new Cookie('ps', '', $cookieLifetime);
        $templateMiss = ConfigurationCore::get('MISSED_TICKET_TEMPLATE', (int)$cookie->id_lang);
        $data = array();
        
        if (!isset($namemode)) $namemode = '--name_mode--';
        if (!isset($content)) $content = '--content--';
        
        $arrayfrom = array("{name_staff}", "{name_moderator}", "{name_customer}", "{email_customer}", "{content}");
        $arrayto   = array($emailName, $namemode, $customer_name, $customer_email, $content);
        $templateMiss = str_replace($arrayfrom, $arrayto, $templateMiss);
        
        if (isset($templateMiss) AND $templateMiss!='')
        	$data['{content}'] = $templateMiss;
        else 
        	$data['{content}'] = 'HI! you will miss ticket.';
        	
        $path=_PS_ROOT_DIR_."/modules/zhelpdesk/mails/";
        /* sent notify to staff or department moderator */
        $sent = ZemailSend::Send(
        		1, 		/* id lang */
        		'templateEmail', 	/* template NOT */
        		$subject,	//Mail::l('Missed ticket'),  /* subject */
        		$data, 
        		$email, 
        		$emailName, 
        		NULL, 	/* $from_mail */ 
        		NULL, 	/* $name mail sending */ 
        		NULL,	/* file attachments */
        		NULL,	/* modeSMTP */
        		$path	/* templatePath */
        	);
         if ($sent)
        	echo 'succesfully!';
        else 
        	echo 'false';
	}
}

$run = new ZnotificationEmail;
$run->runCron();